<template>
  <div class="tab-content creeling-prediction">
    <BasicCard style="height: 100%">
      <BasicVxeTable ref="gridRef" v-bind="gridOption">
        <template #stateSlot="{ row }">
          <el-tag effect="dark" :color="zhuanTai.color(row.stateCode)">
            {{ zhuanTai.text(row.stateCode, '粗纱') }}
          </el-tag>
        </template>

        <template #operationSlot="{ row }">
          <template v-if="editStatus && editIndex == row.machineNo">
            <el-button
              color="#E7E7E7"
              dark
              type="primary"
              size="small"
              @click="cancelRowEvent(row)"
              style="color: #000"
            >
              取消
            </el-button>
            <el-button color="#78BE20" type="primary" size="small" @click="saveRowEvent(row)">
              保存
            </el-button>
          </template>
          <template v-else>
            <el-button
              color="#0FA5DB"
              type="primary"
              :icon="Document"
              size="small"
              @click="handleChangeSpinning(row)"
            >
              改纺
            </el-button>
            <el-button
              color="#539BFF"
              type="primary"
              :icon="Refresh"
              size="small"
              @click="handleInit(row)"
              >初始化</el-button
            >
          </template>
        </template>

        <template #lengthSlot="{ row }">
          <template v-if="['change', 'init'].includes(editStatus) && editIndex == row.machineNo">
            <el-input-number
              v-model="row.theoreticalCsFixLength"
              size="small"
              :controls="false"
              style="width: 100px"
            ></el-input-number>
          </template>
          <span v-else>{{ row.theoreticalCsFixLength }}</span>
        </template>

        <template
          v-for="(item, index) in remainCntNum"
          :key="item"
          v-slot:[`rowSlot${index+1}`]="{ row }"
        >
          <template v-if="editStatus == 'init' && editIndex == row.machineNo">
            <el-input-number
              v-model="row.rowDetail[index].remainCnt"
              size="small"
              :controls="false"
              style="width: 100px"
            ></el-input-number>
          </template>
          <template v-else>
            <span :style="{ color: row.rowDetail[index].remainCnt > 5 ? '#FF2A2A' : '#78BE20' }">{{
              row.rowDetail[index].remainCnt
            }}</span>
          </template>
        </template>
      </BasicVxeTable>
    </BasicCard>
  </div>
</template>

<script setup lang="ts">
  import dayjs from 'dayjs'
  import { zhuanTai } from '@/utils/custom/index'
  import type { VxeGridProps } from 'vxe-table'
  import { ElMessage } from 'element-plus'
  import { CreelingRowVO, RovingRenewCs } from '../../types'
  import { CreelingTableColumns } from '../../data'
  import { getHuoQuHuanTongYuCeList, postGaiFangChuShaShengYuLuoShu } from '@/api/shengChanJianShi'
  import { Document, Refresh } from '@element-plus/icons-vue'

  const remainCntNum = ref()
  const editIndex = ref()
  const gridRef = ref<BasicGridInstance>()

  const editStatus = ref<any>(false)

  const gridOption = reactive<VxeGridProps<CreelingRowVO>>({
    // maxHeight: 500,
    keepSource: true,
    proxyConfig: {
      //   autoLoad: false,
      ajax: {
        query: () => {
          // 默认接收 Promise<any[]>
          return getCreelingList()
        }
      }
    }
  })

  const getCreelingList = () => {
    let tempColumns: any = []
    return new Promise<CreelingRowVO>((resolve) => {
      getHuoQuHuanTongYuCeList().then((res: any) => {
        tempColumns = [...CreelingTableColumns]
        for (let i = 1; i < res.remainCnt + 1; i++) {
          tempColumns.push({
            title: '第' + `${i}排`,
            field: `row${i}`,
            minWidth: 100,
            slots: { default: `rowSlot${i}` }
          })
        }
        tempColumns.push({
          title: '操作',
          field: 'operation',
          width: 180,
          slots: { default: 'operationSlot' }
        })
        gridOption.columns = tempColumns
        remainCntNum.value = res.remainCnt
        resolve(
          res.rovingRenewCs.map((value) => {
            let rowDetail: any = []
            if (value.rowDetail.length == 0 || value.rowDetail == null) {
              for (let i = 0; i < res.remainCnt; i++) {
                rowDetail.push({
                  rowNumber: i + 1,
                  remainCnt: null,
                  predictionChangeTimeNext: null
                })
              }
            }
            return {
              ...value,
              predictionChangeTimeNext:
                value.predictionChangeTimeNext == null
                  ? ''
                  : dayjs(value.predictionChangeTimeNext).format('YYYY-MM-DD HH:mm'),
              rowDetail:
                value.rowDetail.length == 0 || value.rowDetail == null ? rowDetail : value.rowDetail
            }
          })
        )
      })
    })
  }

  // 改纺
  const handleChangeSpinning = (row: RovingRenewCs) => {
    clearInterval(clearTimeSet.value)
    editIndex.value = row.machineNo
    editStatus.value = 'change'
  }
  // 初始化
  const handleInit = (row: RovingRenewCs) => {
    clearInterval(clearTimeSet.value)
    editIndex.value = row.machineNo
    editStatus.value = 'init'
  }

  const saveRowEvent = (row: RovingRenewCs) => {
    // const $grid = gridRef.value?.$grid
    postGaiFangChuShaShengYuLuoShu({
      machineDocumentId: row.machineDocumentId,
      theoreticalCsFixLength: row.theoreticalCsFixLength,
      rowChangeModeCs: editStatus.value == 'change' ? 1 : 2,
      rowDetails: row.rowDetail.map((value) => {
        return {
          rowNumber: value.rowNumber,
          remainCnt: value.remainCnt
        }
      })
    })
      .then(() => {
        editStatus.value = false
        timerFunc()
        ElMessage.success('修改成功！')
      })
      .catch(() => {
        editStatus.value = false
        timerFunc()
        // this.dingShiQi()
      })
  }

  const cancelRowEvent = (row: RovingRenewCs) => {
    editStatus.value = false
    timerFunc()
    const $grid = gridRef.value?.$grid
    $grid?.revertData(row)
  }

  const clearTimeSet = ref()
  const timerFunc = () => {
    clearTimeSet.value = setInterval(() => {
      gridRef.value?.$grid?.commitProxy('query')
    }, 60000)
  }

  onMounted(() => {
    timerFunc()
  })

  onUnmounted(() => {
    clearInterval(clearTimeSet.value)
  })
</script>
